package com.itheima.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.order.entity.OrderEntity;
import com.itheima.order.mapper.OrderMapper;
import com.itheima.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    private boolean flag;

    @Override
    public boolean addOrder(OrderEntity orderEntity) {

        try {
            orderEntity.setIsDel(0);
            int insertResult = orderMapper.insert(orderEntity);

            if (insertResult>=1){
                //基础同步消息发送消息
                //SendResult sendResult = rocketMQTemplate.syncSend("order3-topic:stock", JSON.toJSON(orderEntity));

                //指定自定义标识，向stock服务发送消息
                //SendResult sendResult = rocketMQTemplate.syncSend("order-dlq-topic6:stock", JSON.toJSON(orderEntity));

                //发送订单延迟消息
                //封装消息对象
                //Message message = new Message();
                //message.setBody(JSON.toJSONString(orderEntity).getBytes(StandardCharsets.UTF_8));
                /**
                 * destination: 目的地，topic:tag
                 * message: 消息体
                 * timeout：发送消息超时时间
                 * delayLevel：延迟等级,当为0代表不延迟
                 */
                //SendResult sendResult = rocketMQTemplate.syncSend("order-topic:stock", message, 5000, 4);

                //有序消息
               /*SendResult sendResult = null;
                for (int i = 0; i < 10; i++) {
                    *//**
                    destination：消息目的地
                    payload：消息内容
                    hashKey：该值用于判断当前消息会进入哪个队列，计算公式：传入值%队列总数=队列id，如6%4=2，值进入id为2的队列
                    *//*
                    sendResult = rocketMQTemplate.syncSend("order-topic:stock", i+"");
                }*/


                //生产者-消息幂等性解决方案
                Message message = new Message();
                message.setBody(JSON.toJSONString(orderEntity).getBytes(StandardCharsets.UTF_8));
                message.setKeys(UUID.randomUUID().toString());
                SendResult sendResult = rocketMQTemplate.syncSend("order-message:stock", message);


                SendStatus sendStatus = sendResult.getSendStatus();
                if (!(0 == sendStatus.ordinal())){
                    log.error("消息发送失败");
                    return flag;
                }
                flag=true;
                return flag;
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        }

        return flag;
    }

    @Override
    @Transactional
    public boolean delOrder(Integer id) {

        //查询订单信息
        OrderEntity orderEntity = orderMapper.selectById(id);

        //通知库存服务
        /*Message message = new Message();
        message.setBody(JSON.toJSONString(orderEntity).getBytes(StandardCharsets.UTF_8));
        rocketMQTemplate.syncSend("order-del-topic:stock",message);*/
        //发送事务消息
        org.springframework.messaging.Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(orderEntity)).build();
        TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction("order-del-topic:stock", message, null);
        if (sendResult.getSendStatus().ordinal() ==1){
            return false;
        }
        return true;
    }
}
